package com.srcgen;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.srcgen.builder.ParentConfig;
import com.srcgen.builder.TemplateMapBuilder;
import com.srcgen.dao.IAutoGenDAO;
import com.srcgen.domain.TableColumnsDO;
import com.srcgen.domain.entity.TableEntity;
import com.srcgen.utils.FileCreateUtils;

import freemarker.template.Template;

public class SrcGenMain {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		
		BeanFactory beanFactory=new ClassPathXmlApplicationContext(new String[] {
				"dao/autogen-mybatis-datasource.xml",
				"dao/autogen-mybatis-dao.xml",
				"root-context.xml"
				});
		System.out.println("..SRC AUTO GEN START..");
		
		IAutoGenDAO iAutoGenDAO=(IAutoGenDAO)beanFactory.getBean("iAutoGenDAO");
		HashMap<String, Object> genInfo=(HashMap<String,Object>)beanFactory.getBean("genInfo");
		FreeMarkerConfigurer freemarkerConfig=(FreeMarkerConfigurer)beanFactory.getBean("freemarkerConfig");
		//freemarkerConfig.getConfiguration().
		//foreach table name

		String projectRoot = (String) genInfo.get("projectRoot");
		TableEntity tableProfileDO=null;
		List<TableColumnsDO> tableColumnsDOList=null;
		for(String tableInfo : (List<String>) genInfo.get("tableList")){
			//增加对某些表含sn字段的处理
			String[] tableInfoArray=StringUtils.split(tableInfo, ",");
			String tableName=tableInfoArray[0].trim();
			String projectName=tableInfoArray[1].trim();
			String dbName = tableInfoArray[2].trim();


			//查询表
			tableProfileDO=iAutoGenDAO.findTableProfile(tableName,dbName);
			//查询表字段
			tableColumnsDOList=iAutoGenDAO.listTableColumns(tableName,dbName);

             Map<String,ParentConfig> map = new TemplateMapBuilder()
					.setProjectRoot(projectRoot)
					.setTableName(tableName)
					.setProjectName(projectName)
					.setTableInfo(tableProfileDO)
					.setColumnList(tableColumnsDOList)
					.build();
			for(String configKey:map.keySet()){
				ParentConfig config = map.get(configKey);
				Template template = freemarkerConfig.getConfiguration().getTemplate(config.getTemplateDir());
				String tempStr=FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
				//System.out.println(tempStr);
	
				FileCreateUtils.saveSrcToUtf8File(config.getSaveDir()+config.getClassName()+ ".java", tempStr);
			}

		}
	
		System.out.println("..SRC AUTO GEN  END ..");
	}
	
	
	
}
